import { TabBar } from 'antd-mobile'
// 字体图标的样式
import '../assets/iconfonts/iconfont.css'
// 导入模块化样式
import styles from './css/MyTabbar.module.css'
import { useLocation, useNavigate } from 'react-router-dom'
import { useMemo } from 'react'

// 数据源
const tabs = [
  {
    key: '/home',
    title: '首页',
    icon: <span className="iconfont icon-home"></span>
  },
  {
    key: '/order',
    title: '订单',
    icon: <span className="iconfont icon-order"></span>
  },
  {
    key: '/chat',
    title: '客服',
    icon: <span className="iconfont icon-kefu"></span>
  },
  {
    key: '/me',
    title: '我的',
    icon: <span className="iconfont icon-User"></span>
  }
]

function MyTabbar() {
  // 编程式导航的 Hook
  const nav = useNavigate()
  const location = useLocation()

  // React 计算属性
  // 对函数缓存，用 useCallback
  // 对值进行缓存，才用 useMemo
  const pathname = useMemo(() => {
    if (tabs.some((item) => item.key === location.pathname)) {
      return location.pathname
    } else {
      return '/home'
    }
  }, [location.pathname])

  // console.log(pathname())

  return (
    <div className={styles.box}>
      <TabBar
        activeKey={pathname}
        onChange={(key) => {
          // 拿到的形参 key 就是要调到的路由地址
          nav(key)
        }}
      >
        {/* 循环创建 tabbar 的 Item 项 */}
        {tabs.map((item) => (
          <TabBar.Item
            key={item.key}
            icon={item.icon}
            title={item.title}
          />
        ))}
      </TabBar>
    </div>
  )
}

export default MyTabbar
